import copy
import json
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
from django.http import JsonResponse
from django.views import View
from myapp.models import allmenus, UserInfo, rolename, rolemenus


class rolesoperate(View):
    @method_decorator(csrf_exempt)
    def dispatch(self, request, *args, **kwargs):
        action = kwargs.pop('action', None)
        if action == 'showaddmenus':
            return self.showaddmenus(request, *args, **kwargs)
        elif action == 'addmenus':
            return self.addmenus(request, *args, **kwargs)
        elif action == 'menus':
            return self.menus(request, *args, **kwargs)
        # elif action == 'rolepermissionshow':
        #     return self.rolepermissionshow(request, *args, **kwargs)
        elif action == 'getrole':
            return self.getrole(request, *args, **kwargs)
        elif action == 'addrole':
            return self.addrole(request, *args, **kwargs)
        elif action == 'delrole':
            return self.delrole(request, *args, **kwargs)
        elif action == 'edituserrole':
            return self.edituserrole(request, *args, **kwargs)
        elif action == 'editrole':
            return self.editrole(request, *args, **kwargs)
        elif action == 'editright':
            return self.editright(request, *args, **kwargs)
        elif action == 'getRightsList':
            return self.getRightsList(request, *args, **kwargs)
        elif action == 'addrights':
            return self.addrights(request, *args, **kwargs)
        elif action == 'delrights':
            return self.delrights(request, *args, **kwargs)
        elif action == 'showeditrights':
            return self.showeditrights(request, *args, **kwargs)
        elif action == 'showroleEdit':
            return self.showroleEdit(request, *args, **kwargs)
        else:
            return super().dispatch(request, *args, **kwargs)

    # @csrf_exempt
    # def rolepermissionshow(self, request, *args, **kwargs):
    #     a = []
    #     records = allmenus.objects.values('menus')
    #     for i in list(records):
    #         a.append(i['menus'])
    #     return JsonResponse(a, safe=False)

    @csrf_exempt
    def editrole(self, request, *args, **kwargs):
        data = json.loads(request.body)
        role = data.get('role')
        rolegrade = data.get('rolegrade')
        grade = data.get('grade')
        id = data.get('id')
        date1 = {
            'role': role,
            "rolegrade": rolegrade,
            "grade":grade
        }
        rolename.objects.filter(id=id).update(**date1)
        return JsonResponse({'message': '修改成功'})

    @csrf_exempt
    def editright(self, request, *args, **kwargs):
        data = json.loads(request.body)
        menus = data.get('menus')
        menusid = data.get('menusid')
        grade = data.get('grade')
        id = data.get('id')
        date1 = {
            'menus': menus,
            "menusid": menusid,
            "grade":grade
        }
        allmenus.objects.filter(id=id).update(**date1)
        return JsonResponse({'message': '修改成功'})

    def remove_empty_children(self,lst):
        new_list = []
        for item in lst:
            if 'children' in item:
                children = item['children']
                if not children:
                    del item['children']
                else:
                    item['children'] = rolesoperate.remove_empty_children(self,children)
            new_list.append(item)
        return new_list   #去除所有children为空的键值对

    def get_ids_without_children(self,lst):
        result = []
        for item in lst:
            if 'children' not in item:
                result.append(item['id'])
            else:
                children = item['children']
                child_ids = rolesoperate.get_ids_without_children(self,children)
                if len(child_ids) == 0:
                    result.append(item['id'])
                else:
                    result.extend(child_ids)
        return result #找到所有没有children键的字典的id值

    @csrf_exempt
    def showaddmenus(self, request, *args, **kwargs):
        allmenu = self.getmenus(allmenus)
        data = json.loads(request.body)
        role = data.get('role')
        existmenu = self.getmenus1(role)#这里的role也就是permission
        new_list = self.remove_empty_children(existmenu)
        li = self.get_ids_without_children(new_list)
        data = {
            'all' : allmenu,
            'exist': li,
        } #返回所有权限，以及已经拥有的权限，用于在前端展示默认勾选
        return JsonResponse(data, safe=False,status=200)

    @csrf_exempt
    def showroleEdit(self, request, *args, **kwargs):
        data = json.loads(request.body)
        role = data.get('role')
        Rolename = rolename.objects.get(role=role)
        rolegrade = Rolename.rolegrade
        grade = Rolename.grade
        return JsonResponse({'role': role,'rolegrade':rolegrade,'grade':grade,'id':Rolename.id})

    def addrolemenus(self,role,li):
        # 清空数据库
        rolemenus.objects.filter(role=role).delete()
        addmenus = allmenus.objects.filter(id__in=li)
        for menu in addmenus:
            admin_menu = rolemenus(
                role=role,
                id=menu.id,
            )
            admin_menu.save(force_insert=True)
        return True #重新写入数据库权限

    @csrf_exempt
    def addmenus(self, request, *args, **kwargs):#更改角色所拥有权限，因为是清空数据库重新写入，所以叫addmenus
        data = json.loads(request.body)
        rids = data.get('rids')#这里rids就是allmenus里面的id，将rids加上对应的role类型存到rolemenus里去，
        role = data.get('role') #之后读取某个角色的权限就是根据rolemenus里的id去匹配allmenus里的数据
        if rids == '':
            rolemenus.objects.filter(role=role).delete()
            return JsonResponse({})
        li = [int(x) for x in rids.split(',')]
        self.addrolemenus(role,li)
        return JsonResponse({})

    @csrf_exempt
    def addrole(self, request, *args, **kwargs):
        data = json.loads(request.body)
        role = data.get('rolename')
        grade = data.get('grade')
        rolegrade = data.get('rolegrade')
        admin_menu = rolename(
            role=role,
            rolegrade=rolegrade,
            grade=grade
        )
        admin_menu.save(force_insert=True)
        return JsonResponse({})

    @csrf_exempt
    def delrole(self, request, *args, **kwargs):
        data = json.loads(request.body)
        role = data.get('role')
        rolename.objects.filter(role=role).delete()
        rolemenus.objects.filter(role=role).delete()
        return JsonResponse({})

    def getmenus(self,db):
        records = list(db.objects.values('id', 'menus', 'menusid'))
        for i in records:
            a = []
            for x in records:
                if str(i['id']) == x['menusid']:
                    a.append(x)
            i.update({'children': a})
        record = copy.deepcopy(records)
        for i in record:
            if i['menusid'] != '':
                records.remove(i)
        return records

    def getmenus1(self,permission):
        role_menus = rolemenus.objects.filter(role=permission)
        menu = []
        for i in role_menus:
                menu.append(i.id)
        recor = list(allmenus.objects.values('id', 'menus', 'menusid'))
        records = []
        for i in recor:
            if i['id'] in menu:
                records.append(i)
        for i in records:
            a = []
            for x in records:
                if str(i['id']) == x['menusid']:
                    a.append(x)
            i.update({'children': a})
        record = copy.deepcopy(records)
        for i in record:
            if i['menusid'] != '':
                records.remove(i)
        return records

    @csrf_exempt
    def menus(self, request, *args, **kwargs):
        data = json.loads(request.body)
        cardid = data.get('cardid')
        user_info = UserInfo.objects.get(cardid=cardid)
        permission = user_info.permission
        records = self.getmenus1(permission)
        # print(records)
        return JsonResponse(records, safe=False)

    def edituserrole(self,request, *args, **kwargs):
        data = json.loads(request.body)
        rid = data.get('rid')
        cardid = data.get('cardid')
        user_info = UserInfo.objects.get(cardid=cardid)
        user_info.permission = rid
        user_info.save()
        return JsonResponse({},status=200)

    def getrole(self,request, *args, **kwargs):
        roles = rolename.objects.values('role','rolegrade','grade')
        sorted_data = sorted(list(roles), key=lambda x: int(x['grade']))
        return JsonResponse(sorted_data, safe=False,status=200)

    def getRightsList(self,request, *args, **kwargs):
        data = json.loads(request.body)
        menus = allmenus.objects.values('menus','id','menusid','grade')
        # new_list = [{'url': f"{item['menusid']}-{item['id']}",'id':item['id'], 'menus': item['menus'],'grade':item['grade']} for item in list(menus) if
        #             item['id'] and item['menusid']]
        pagenum = data.get('pagenum') - 1
        pagesize = data.get('pagesize')
        li = [menus[i:i + pagesize] for i in range(0, len(menus), pagesize)]
        data = {
            "results": li[pagenum],
            "total": len(menus)
        } #权限页分页
        return JsonResponse(data, safe=False,status=200)

    @csrf_exempt
    def addrights(self, request, *args, **kwargs):
        data = json.loads(request.body)
        id = data.get('id')
        menus = data.get('menus')
        menusid = data.get('menusid')
        grade = data.get('grade')
        new_obj = allmenus()
        new_obj.id = id
        new_obj.menus = menus
        new_obj.menusid = menusid
        new_obj.grade = grade
        new_obj.save()
        return JsonResponse({})

    @csrf_exempt
    def delrights(self, request, *args, **kwargs):
        data = json.loads(request.body)
        id = int(data.get('id'))
        try:
            all_instance = allmenus.objects.filter(id=id)
            role_instance = rolemenus.objects.filter(id=id)
            all_instance.delete()
            role_instance.delete()
        except rolemenus.DoesNotExist:
            all_instance = allmenus.objects.filter(id=id)
            all_instance.delete()
            return JsonResponse({},status=200)
        return JsonResponse({})

    @csrf_exempt
    def showeditrights(self, request, *args, **kwargs):
        data = json.loads(request.body)
        id = int(data.get('id'))
        all_instances = allmenus.objects.get(id=id)
        # menus = data.get('menus')
        # menusid = data.get('menusid')
        # garde = data.get('garde')
        return JsonResponse({'id':id,'menus':all_instances.menus,'menusid':all_instances.menusid,'grade':all_instances.grade})